

import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;// import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;// import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;// import javax.swing.JTextPane;
import javax.swing.border.Border;//import com.simulacra.applet.OutputPanel;
import com.simulacra.applet.WinnerListener;
import com.simulacra.model.EventGenerator;
import com.simulacra.model.PlayoffSoccerGame;
import com.simulacra.model.SoccerEvent;
import com.simulacra.model.SoccerEventGenerator;
import com.simulacra.model.SoccerGame;
import com.simulacra.model.SoccerTeam;
import com.simulacra.model.Team;// import com.simulacra.util.log.Logger;
/**
 * Clase Inicial que contiene y muestra la Interfaz Grafica al Usuario,
 * carga los valores iniciales tomados del documento HTML e inicializa
 * los objetos requeridos para la aplicacion.
 *
 */
public class Application extends Applet implements ActionListener , WinnerListener {

	private static final long serialVersionUID = 1L;
	public static String HEADER_LABEL= "Simulacion : Luiguilla Mexicana";
	public static String TITLE= " Competition: Final Teams";
	private JTextArea output= null; 
	public JPanel headerPanel;
	public JPanel livePanel= null;
	public JPanel organigram = null;
	JPanel firstRound= null;
	JPanel semiFinalRound= null;
	JPanel finalRound= null;
	JPanel champRound= null;
	public JButton playPauseButton= null;
	public JButton local= null;
	public JButton visitor= null;
	public JPanel main = null;
	public Border blacklineBorder= null;
	public static final String BUTTON_LABEL= "Play/Pause";
	public static final String DEFAULT_LOCAL_TEAM_NAME= "Monterrey";
	public static final String DEFAULT_VISITOR_TEAM_NAME= "Tigres";
	private static final String MESSAGE_PREFIX = ":";
	public static Dimension PREFERED_TEXTAREA_DIMENSION= new Dimension(250, 250);
	public static Dimension PREFERED_APPLET_DIMENSION= new Dimension(800, 800);
	public final double DEFAULT_TEAM_AVERAGE= 0.5;
	public final double DEFAULT_GOAL_AVERAGE= 0.05;
	private int index= 0;
	List<Team> team= null;
	List<Team> nextRoundTeam= null;// PREFERED_APPLET_DIMENSION
	EventGenerator generator;
	 // Your image name; Image anyGif;

// The applet base URL URL point;

// This object will allow you to control loading 
    MediaTracker mt;
	public void init () {


		setBackground(Color.yellow);
		setLayout(new BorderLayout());
		blacklineBorder = BorderFactory.createLineBorder(Color.black, 2);
		main= new JPanel ();main.setLayout(new BorderLayout());
		main.setBorder(blacklineBorder);
		main.add(createHeaderPane(), BorderLayout.NORTH);

		main.add(createCenterPane(), BorderLayout.CENTER);
		main.add(new JLabel("-"), BorderLayout.SOUTH);
		main.add(new JLabel("-"), BorderLayout.EAST);
		main.add(new JLabel("-"), BorderLayout.WEST);

        add(main, BorderLayout.CENTER);
        resize(PREFERED_APPLET_DIMENSION);
		build();
		// team List()
		loadTeam();
		load1stRow();
	}
	
	void build() {
    	String methodName = "build() ";
    	String eventValue= "";
    	Double nextValue= null;
    	int gameLenght =0 ;

		HashMap<String, Double>  map = null;
		map = new HashMap <String, Double> ();
    	log(this, methodName);
    	
		map.put(Team.VISIT_TEAM, new Double (0.2));
		map.put(Team.LOCAL_TEAM, new Double (0.8));
		eventValue= getParameter(SoccerEvent.CORNER_EVENT_LABEL);
		try {
			nextValue= new Double(eventValue);
			log(this , "Load " + SoccerEvent.CORNER_EVENT_LABEL + "-" +nextValue);
		} catch (Exception badArgument) {
			log(this , SoccerEvent.FAULT_EVENT_LABEL + " not defined");	
		}
		map.put(SoccerEvent.CORNER_EVENT_LABEL, nextValue);
		eventValue= getParameter(SoccerEvent.GOL_EVENT_LABEL);
		try {
			nextValue= new Double(eventValue);
			log(this , "Load " + SoccerEvent.GOL_EVENT_LABEL + "-" +nextValue);
		} catch (Exception badArgument) {
			nextValue= new Double(DEFAULT_GOAL_AVERAGE);		
			log(this , "Load (default) " + SoccerEvent.GOL_EVENT_LABEL + "-" +nextValue);
		}
		map.put(SoccerEvent.GOL_EVENT_LABEL, nextValue);
		eventValue= getParameter(SoccerEvent.FAULT_EVENT_LABEL);
		try {
			nextValue= new Double(eventValue);
			map.put(SoccerEvent.FAULT_EVENT_LABEL, nextValue);
			log(this , "Load " + SoccerEvent.FAULT_EVENT_LABEL + "-" +nextValue);
		} catch (Exception badArgument) {
			log(this , SoccerEvent.FAULT_EVENT_LABEL + " not defined");		
		}

		eventValue= getParameter(SoccerEvent.OFFSIDE_EVENT_LABEL);
		try {
			nextValue= new Double(eventValue);
			map.put(SoccerEvent.OFFSIDE_EVENT_LABEL, nextValue);
			log(this , "Load " + SoccerEvent.OFFSIDE_EVENT_LABEL + "-" +nextValue);
		} catch (Exception badArgument) {
			log(this , SoccerEvent.OFFSIDE_EVENT_LABEL + " not defined");		
		}

		eventValue= getParameter(SoccerEvent.AMONESTACION_EVENT_LABEL);
		try {
			nextValue= new Double(eventValue);
			map.put(SoccerEvent.AMONESTACION_EVENT_LABEL, nextValue);
			log(this , "Load " + SoccerEvent.AMONESTACION_EVENT_LABEL + "-" +nextValue);
		} catch (Exception badArgument) {
			log(this , SoccerEvent.AMONESTACION_EVENT_LABEL + " not defined");		
		}

		eventValue= getParameter(SoccerEvent.SHOT_EVENT_LABEL);
		try {
			nextValue= new Double(eventValue);
			map.put(SoccerEvent.SHOT_EVENT_LABEL, nextValue);
			log(this , "Load " + SoccerEvent.SHOT_EVENT_LABEL + "-" +nextValue);
		} catch (Exception badArgument) {
			log(this , SoccerEvent.SHOT_EVENT_LABEL + " not defined");		
		}

		eventValue= getParameter(SoccerEvent.BAND_EVENT_LABEL);
		try {
			nextValue= new Double(eventValue);
			map.put(SoccerEvent.BAND_EVENT_LABEL, nextValue);
			log(this , "Load " + SoccerEvent.BAND_EVENT_LABEL + "-" +nextValue);
		} catch (Exception badArgument) {
			log(this , SoccerEvent.BAND_EVENT_LABEL + " not defined");		
		}

		eventValue= getParameter(SoccerEvent.EVENT_AMOUNT_LABEL);
		try {
			gameLenght= Integer.parseInt(eventValue);//	map.put(SoccerEvent.EVENT_AMOUNT_LABEL, gameLenght);
			log(this , "Load " + SoccerEvent.EVENT_AMOUNT_LABEL + "-" +gameLenght);
		} catch (Exception badArgument) {
			gameLenght= SoccerGame.DEFAULT_EVENT_AMOUNT;
			log(this , SoccerEvent.EVENT_AMOUNT_LABEL + " not defined");		
		}
		generator = new SoccerEventGenerator(map, gameLenght);
	}

	void loadTeam () {
    	String methodName = "loadTeam() ";
    	String teamValue= "";
    	String nextValue= null;
    	boolean nextTeam= true;
    	int index= 1;
    	log(this, methodName);
    	team = new ArrayList<Team>();
    	while (nextTeam) {
    		
    		teamValue= getParameter("team."+ String.valueOf(index));
    		nextValue= getParameter("teamRank."+ String.valueOf(index));
    		if (teamValue == null && nextValue ==null ) {
    			nextTeam= false;
    		} else {
    			team.add(new SoccerTeam(teamValue, nextValue));
    			log(this, "Team "+ teamValue + " loaded (" + nextValue+ ")");
    		}
    		index ++;

    	}


	}
	private JPanel createCenterPane() {
		JPanel centerPanel= null;
		centerPanel= new JPanel();
		centerPanel.setLayout(new BorderLayout());
		centerPanel.add(createLivePane(), BorderLayout.NORTH);
		centerPanel.add(createOrganigramPane(), BorderLayout.CENTER);
		return centerPanel;
	}
	private JPanel createLivePane() {
		JPanel aux = null;
		int columnAmount= 4;
		int rowAmount= 2;
		JScrollPane areaScrollPane= null;
		aux= new JPanel();
		livePanel = new JPanel(); livePanel.setLayout(new GridLayout(rowAmount, 1));
		aux.setLayout(new GridLayout(1, columnAmount));
		playPauseButton= new JButton (BUTTON_LABEL);playPauseButton.addActionListener(this);
		areaScrollPane= new JScrollPane(output= new JTextArea());
		areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		areaScrollPane.setPreferredSize(PREFERED_TEXTAREA_DIMENSION);

		aux.add(new JLabel(""));
		aux.add(playPauseButton);
		aux.add(local= new JButton(""));local.setEnabled(false);
		aux.add(visitor= new JButton(""));visitor.setEnabled(false);
		livePanel.add(aux);
		livePanel.add(areaScrollPane);
		return livePanel;
		
	}	
	private JPanel createHeaderPane() {
		headerPanel= new JPanel();
		headerPanel.add(new JLabel(HEADER_LABEL));
		return headerPanel;
		
	}	
	private JPanel createOrganigramPane() {
		int rowAmount= 4;
		int firstRowColumnAmount= 8;
		int semisRowColumnAmount= 4;
		int finalRowColumnAmount= 2;


		organigram= new JPanel();
		organigram.setLayout(new GridLayout(rowAmount, 1));
		organigram.add(new JLabel(TITLE));
		firstRound = new JPanel ();firstRound.setLayout(new GridLayout(1, firstRowColumnAmount));
		semisRowColumnAmount= load1stRow();
		semisRowColumnAmount = (int)semisRowColumnAmount / 2;
		semiFinalRound = new JPanel ();semiFinalRound.setLayout(new GridLayout(1, semisRowColumnAmount));
		finalRound = new JPanel ();finalRound.setLayout(new GridLayout(1, finalRowColumnAmount));
		champRound = new JPanel ();champRound.setLayout(new GridLayout(1, 1));


		organigram.add(firstRound);
		organigram.add(semiFinalRound);
		organigram.add(champRound);

		return organigram;

	}
	private int load1stRow() {
		int firstRowColumnAmount= 1;
		JButton teamOne;

		// add(ing) team logo
		if (firstRound == null) {
			firstRowColumnAmount= team.size();
			firstRound= new JPanel ();firstRound.setLayout(new GridLayout(1, firstRowColumnAmount));
		}
		for (int i= 0 ;team != null && i < team.size(); i++ ) {
			firstRound.add(teamOne= new JButton(team.get(i).getName()));
			teamOne.setEnabled(false);

		}
		return firstRowColumnAmount;
	}
	private void nextGame () {
    	String methodName = "nextGame() ";
		int i= index ; 
    	SoccerGame game= null;
    	Team localTeam = null; //team.get(0);
    	Team visitorTeam = null;
		HashMap<String, Double>  map = null;
		map = new HashMap <String, Double> ();
    	log(this, methodName);

		if (team != null && i < team.size()- 1 ) {
    		log(this, methodName + "("+ i+ ")");
    		localTeam = team.get(i);
    		visitorTeam = team.get(i +1);
        	local.setText(localTeam.getName());
        	visitor.setText(visitorTeam.getName());
        	log (this, Team.VISIT_TEAM+ visitorTeam.getName()+ " :"+ visitorTeam.getRank()) ;
        	log (this, Team.LOCAL_TEAM+ localTeam.getName()+ " :"+ localTeam.getRank()) ;
    		map.put(Team.VISIT_TEAM, visitorTeam.getRank());
    		map.put(Team.LOCAL_TEAM, localTeam.getRank());
        	game = new PlayoffSoccerGame (localTeam, visitorTeam);
        	generator.setTeamData(map);
        	game.setEventGenerator(generator);
        	game.init(this);
        	index += 2;
		} 		
	}

    public void startCompetition () {
    	String methodName = "startCompetition() ";

    	log(this, methodName);

    	nextGame();

		
	}
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		nextGame();
		
	}
	public String log (Object theSource, String theValue) {
		String finalValue = "";
		if (theSource == null) {
			finalValue= "null " + theValue;
		} else {
			finalValue = theSource.getClass().getName()+ " "+ theValue;
		}
		finalValue= MESSAGE_PREFIX+ theValue+ "\n";
		if (this.output== null) {
			;
		} else {
			output.append(finalValue);
		}//	System.out.println(finalValue);
		return finalValue;
	}

	public void setWinner(Team win) {
    	String methodName = "setWinner() ";// log(this, methodName);
		// TODO Auto-generated method stub
    	if (win == null) {
    		log(this, methodName + "Exception");
    	} else {
    		semiFinalRound.add(new JButton(win.getName()));
    	}
    	if (nextRoundTeam == null) {
    		nextRoundTeam = new ArrayList<Team> ();
    	}//	nextRoundTeam.add(win);
    	repaint();
		
	}
}
